
package com.bear.cmcc.NetTestHTTP;

import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.service.NetUpdateVersionService;
import com.bear.cmcc.NetTestHTTP.ui.view.LoadingDialog;
import com.bear.cmcc.NetTestHTTP.util.MyCommonUtil;
import com.bear.cmcc.NetTestHTTP.util.SetUtil;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

public class SplashScreenActivity extends Activity {

    private LoadingDialog dialog;

    private boolean isNet = false;

    private Message message = null;

    int refresh = 1;

    int autoLogin = 2;

    int showDialog = 3;

    private Handler refreshHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == refresh) {
                String message = (String) msg.obj;
                if (dialog != null) {
                    dialog.updateMessage(message);
                }

            } else if (msg.what == autoLogin) {
                String[] values = SetUtil.getLoginInfo(SplashScreenActivity.this);
                if (values != null && values.length == 2 && !TextUtils.isEmpty(values[0])
                        && !TextUtils.isEmpty(values[1])) {
                    MyCommonUtil.showMessage(SplashScreenActivity.this, R.string.auto_logining);
                    boolean result = MyCommonUtil.startAutoLogin(SplashScreenActivity.this,
                            values[0], values[1]);

                    if (!result) {
                        MyCommonUtil.showLoginDialog(SplashScreenActivity.this);
                    } else {
                        startNextActivity();
                    }
                } else {
                    MyCommonUtil.showLoginDialog(SplashScreenActivity.this);
                }

            } else if (msg.what == showDialog) {
                MyCommonUtil.showLoginDialog(SplashScreenActivity.this);
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash_screen);
        dialog = new LoadingDialog(this);
        checkUpdateVersion();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 检查版本更新
     */
    private void checkUpdateVersion() {
        if (MyCommonUtil.isNetworkAviable(this)) {
            isNet = true;
            IntentFilter filter = new IntentFilter();
            filter.addAction(MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN);
            filter.addAction(MyCommonConstant.PrivateActionName.DOWN_PROCESS_ACTION);
            registerReceiver(receiver, filter);
            if (!isShowUpdate) {
                MyCommonUtil.showMessage(this, R.string.checkingVersion);
                SetUtil.updateNewVersion_FJ(this, false, null);
                isShowUpdate = true;
            }
        } else {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    dealWithLogin();
                }

            }, 3000);
        }
    }

    private StartApkInstallReceiver receiver = new StartApkInstallReceiver();// 广播

    private boolean isShowUpdate = false;// 是否操作了更新

    private boolean isOpenIsUpdate = false;// 是否打开了更新提示

    class StartApkInstallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (MyCommonConstant.PrivateActionName.DOWN_PROCESS_ACTION.equals(intent.getAction())) {
                String process = intent
                        .getStringExtra(MyCommonConstant.PrivateActionName.DOWN_PROCESS);
                String total = intent
                        .getStringExtra(MyCommonConstant.PrivateActionName.DOWN_PROCESS_TOTAL);
                message = new Message();
                message.what = refresh;
                message.obj = String.format(context.getString(R.string.processing), process, total);
                refreshHandler.sendMessage(message);

            } else

            if (intent.getAction()
                    .equals(MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN)) {
                String type = intent
                        .getStringExtra(MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE);
                if (type.equals(MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_CHECK)
                        && !isOpenIsUpdate) {
                    // 版本更新的反馈
                    String updateStatus = intent
                            .getStringExtra(MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE);
                    if (updateStatus
                            .equals(MyCommonConstant.PrivateActionName.NET_WORK_APK_ISUPDATE_YES)) {
                        // 需要更新
                        String Description = intent
                                .getStringExtra(MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS);

                        String downUrl = intent
                                .getStringExtra(MyCommonConstant.PrivateActionName.ALL_APK_DOWN_URL);

                        isOpenIsUpdate = true;
                        SetUtil.openIsUpdateVerion_FJ_Close(context, Description, dialog, true,
                                downUrl, false);
                    } else {
                        String status = intent
                                .getStringExtra(MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS);
                        if ("1".equals(status)) {
                        } else {
                            Toast.makeText(getBaseContext(), "获取版本信息失败", Toast.LENGTH_SHORT).show();
                        }
                        dealWithLogin();
                    }
                } else if (type
                        .equals(MyCommonConstant.PrivateActionName.NET_WORK_APK_DATA_DOWN_TYPE_DOWN)) {
                    // 下载的反馈
                    String downStatus = intent
                            .getStringExtra(MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS);
                    if (downStatus
                            .equals(MyCommonConstant.PrivateActionName.ALL_APK_DOWNSTATUS_YES)) {
                        // 下载成功
                        dialog.dismiss();
                        SetUtil.installNewVersion_FJ(SplashScreenActivity.this, true);
                    } else {
                        // 下载失败
                        dialog.dismiss();
                        Toast.makeText(getBaseContext(), "下载安装文件失败", Toast.LENGTH_LONG).show();
                        dealWithLogin();

                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        try {
            if (isNet && receiver != null) {
                unregisterReceiver(receiver);
            }

            if (refreshHandler != null) {
                refreshHandler.removeMessages(refresh);
                refreshHandler.removeMessages(autoLogin);
                refreshHandler.removeMessages(showDialog);
                refreshHandler = null;
            }
            Intent intent = new Intent(this, NetUpdateVersionService.class);
            stopService(intent);
        } catch (Exception e) {

        }
        super.onDestroy();

    }

    /**
     * 出来登录。
     */
    public void dealWithLogin() {

        Toast.makeText(getBaseContext(), "检查当前是否已经登录", Toast.LENGTH_LONG).show();
        MyCommonUtil.checkHaveLogin(SplashScreenActivity.this);
//        //测试需要去掉 默认登录成功，没有用户名和
//        NetworkTestApp.getApp().setHaveLogin(true);// 用来记录已经登录
        if (!NetworkTestApp.getApp().isHaveLogin()) {

            if (SetUtil.getIsAuToLogin(this)) {

                refreshHandler.sendEmptyMessage(autoLogin);
            } else {
                refreshHandler.sendEmptyMessage(showDialog);
            }
        } else {
            startNextActivity();
        }
    }

    public void startNextActivity() {
        // startActivity(new Intent(SplashScreenActivity.this,
        // NationalInfoActivity.class));
        // finish();
        // new LoginVerifyTask(this).execute();
        Log.e("scj", "开始启动下一个界面");

        MyCommonUtil.startFjActivity(SplashScreenActivity.this);
        this.finish();
    }

}
